import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Row, Col, Card, Button, Tag, Avatar, Tabs, List, Rate, Divider, message } from 'antd';
import {
  BookOutlined,
  UserOutlined,
  ClockCircleOutlined,
  EyeOutlined,
  StarOutlined,
  PlayCircleOutlined,
  HeartOutlined,
  ShareAltOutlined,
} from '@ant-design/icons';
import { courseAPI } from '../../utils/api';
import useAuthStore from '../../stores/authStore';
import './Detail.scss';

const { TabPane } = Tabs;

const CourseDetail = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const { user, isAuthenticated } = useAuthStore();
  const [course, setCourse] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchCourseDetail();
  }, [id]);

  const fetchCourseDetail = async () => {
    try {
      setLoading(true);
      const response = await courseAPI.getCourse(id);
      setCourse(response.data);
    } catch (error) {
      console.error('Failed to fetch course detail:', error);
      message.error('获取课程详情失败');
    } finally {
      setLoading(false);
    }
  };

  const handleBuyCourse = async () => {
    if (!isAuthenticated) {
      message.warning('请先登录');
      navigate('/login');
      return;
    }

    try {
      await courseAPI.buyCourse(id);
      message.success('购买成功');
      navigate(`/courses/${id}/learn`);
    } catch (error) {
      message.error('购买失败');
    }
  };

  const handleFavorite = () => {
    message.info('收藏功能开发中');
  };

  const handleShare = () => {
    message.info('分享功能开发中');
  };

  if (loading) {
    return (
      <div className="loading-container">
        <div>加载中...</div>
      </div>
    );
  }

  if (!course) {
    return (
      <div className="error-container">
        <div>课程不存在</div>
      </div>
    );
  }

  const renderCourseHeader = () => (
    <Card className="course-header">
      <Row gutter={[24, 24]}>
        <Col xs={24} md={8}>
          <div className="course-cover">
            <img src={course.cover_image} alt={course.title} />
            <div className="course-overlay">
              <PlayCircleOutlined />
            </div>
          </div>
        </Col>
        <Col xs={24} md={16}>
          <div className="course-info">
            <h1>{course.title}</h1>
            <p className="course-description">{course.description}</p>
            
            <div className="course-meta">
              <div className="meta-item">
                <UserOutlined />
                <span>讲师：{course.teacher?.nickname}</span>
              </div>
              <div className="meta-item">
                <BookOutlined />
                <span>{course.lesson_count} 课时</span>
              </div>
              <div className="meta-item">
                <ClockCircleOutlined />
                <span>{course.duration}</span>
              </div>
              <div className="meta-item">
                <EyeOutlined />
                <span>{course.view_count} 人学习</span>
              </div>
              <div className="meta-item">
                <StarOutlined />
                <span>{course.rating} 分</span>
              </div>
            </div>

            <div className="course-tags">
              {course.tags?.map((tag, index) => (
                <Tag key={index} color="blue">{tag}</Tag>
              ))}
            </div>

            <div className="course-price">
              <span className="current-price">¥{course.price}</span>
              {course.original_price && (
                <span className="original-price">¥{course.original_price}</span>
              )}
            </div>

            <div className="course-actions">
              <Button
                type="primary"
                size="large"
                onClick={handleBuyCourse}
                icon={<BookOutlined />}
              >
                立即购买
              </Button>
              <Button
                size="large"
                onClick={handleFavorite}
                icon={<HeartOutlined />}
              >
                收藏
              </Button>
              <Button
                size="large"
                onClick={handleShare}
                icon={<ShareAltOutlined />}
              >
                分享
              </Button>
            </div>
          </div>
        </Col>
      </Row>
    </Card>
  );

  const renderCourseContent = () => (
    <Card className="course-content">
      <Tabs defaultActiveKey="overview" size="large">
        <TabPane tab="课程介绍" key="overview">
          <div className="course-overview">
            <h3>课程简介</h3>
            <p>{course.description}</p>
            
            <h3>学习目标</h3>
            <ul>
              {course.learning_objectives?.map((objective, index) => (
                <li key={index}>{objective}</li>
              ))}
            </ul>

            <h3>适合人群</h3>
            <p>{course.target_audience}</p>
          </div>
        </TabPane>
        
        <TabPane tab="课程大纲" key="outline">
          <div className="course-outline">
            <List
              itemLayout="horizontal"
              dataSource={course.lessons || []}
              renderItem={(lesson, index) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={
                      <div className="lesson-number">
                        {index + 1}
                      </div>
                    }
                    title={lesson.title}
                    description={
                      <div>
                        <span>{lesson.duration}</span>
                        {lesson.is_free && <Tag color="green">免费</Tag>}
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
          </div>
        </TabPane>
        
        <TabPane tab="学员评价" key="reviews">
          <div className="course-reviews">
            <div className="reviews-summary">
              <div className="rating-overview">
                <div className="average-rating">
                  <span className="rating-score">{course.rating}</span>
                  <Rate disabled defaultValue={course.rating} />
                  <span className="rating-count">({course.review_count} 条评价)</span>
                </div>
              </div>
            </div>
            
            <List
              itemLayout="horizontal"
              dataSource={course.reviews || []}
              renderItem={(review) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={
                      <Avatar src={review.user?.avatar} icon={<UserOutlined />} />
                    }
                    title={
                      <div>
                        <span>{review.user?.nickname}</span>
                        <Rate disabled defaultValue={review.rating} size="small" />
                      </div>
                    }
                    description={
                      <div>
                        <p>{review.content}</p>
                        <span className="review-time">{review.created_at}</span>
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
          </div>
        </TabPane>
      </Tabs>
    </Card>
  );

  return (
    <div className="course-detail-page">
      {renderCourseHeader()}
      {renderCourseContent()}
    </div>
  );
};

export default CourseDetail; 